package com.arvato.common.webservice.pos;

import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSASignature {

	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private Base64 base64 = new Base64();

	public String sign(Object... contents) {
		StringBuilder content = new StringBuilder(1024);
		for (int i = 0; i < contents.length - 1; i++) {
			content.append(contents[i]).append("&");
		}
		content.deleteCharAt(content.length() - 1);
		String str = content.toString();
		// log.info("待签名字符串:{}", str);
		String privateKey = (String) contents[contents.length - 1];
		return doSign(str, "UTF-8", privateKey);
	}

	/**
	 * RSA签名
	 * 
	 * @param content
	 *            待签名数据
	 * @param encode
	 *            字符集编码
	 * @return 签名值
	 */
	public String doSign(String content, String encode, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(encode));

			byte[] signed = signature.sign();

			String sign = base64.encodeAsString(signed);
			// log.info("rsa签名:{}", sign);
			return sign;
		} catch (Exception e) {
			// log.error("rsa签名异常:", e);
			throw new RuntimeException(e);
		}
	}

}
